<template>
  <header id="header">
    <h2>问卷博客平台</h2>
    <div class="nav-links">
      <router-link to="/" custom v-slot="{navigate}">
        <h3 @click="navigate">首页</h3>
      </router-link>
      <router-link to="/questionnaires" custom v-slot="{navigate}">
        <h3 @click="navigate">问卷中心</h3>
      </router-link>
      <router-link to="/blog" custom v-slot="{navigate}">
        <h3 @click="navigate">博客中心</h3>
      </router-link>
    </div>
    <div class="user-info">
      <img :src="userInfo.avatarUrl || defaultAvatar" class="avatar" @click="showUserMenu = !showUserMenu">
      <div class="user-menu" v-if="showUserMenu">
        <router-link to="/profile">个人中心</router-link>
        <template v-if="userInfo.isAdmin">
          <router-link to="/admin/users">用户管理</router-link>
          <router-link to="/admin/applications">审核申请</router-link>
        </template>
        <a @click="logout">退出登录</a>
      </div>
    </div>
  </header>
</template>

<script>
export default {
  name: 'HeaderComponent',
  data() {
    return {
      showUserMenu: false,
      defaultAvatar: '/default-avatar.png'
    }
  },
  computed: {
    userInfo() {
      return this.$store?.state?.currentUser || JSON.parse(localStorage.getItem('currentUser') || '{}')
    }
  },
  methods: {
    logout() {
      localStorage.removeItem('currentUser')
      window.location.href = '/login';
      // 如果 store 可用，也更新 store
      if (this.$store?.commit) {
        this.$store.commit('updateUser', {})
      }
    }
  }
}
</script>

<style lang="scss" scoped>
#header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  padding: 0 20px;
  background-color: #ee7419;
  color: #fff;

  .nav-links {
    display: flex;
    gap: 20px;
    
    h3 {
      cursor: pointer;
      &:hover {
        text-decoration: underline;
      }
    }
  }

  .user-info {
    position: relative;
    
    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      cursor: pointer;
      object-fit: cover;
      border: 2px solid #fff;
    }

    .user-menu {
      position: absolute;
      top: 50px;
      right: 0;
      background: white;
      border-radius: 4px;
      box-shadow: 0 2px 12px rgba(0,0,0,0.1);
      padding: 5px 0;
      z-index: 1000;
      
      a {
        display: block;
        padding: 8px 20px;
        color: #333;
        text-decoration: none;
        cursor: pointer;
        
        &:hover {
          background: #f5f5f5;
        }
      }
    }
  }

  h2 {
    font-size: 20px;
    font-weight: bold;
  }

  h3 {
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
}
</style>
